package com.lagou.web;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.lagou.service.CheckService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;


public class CheckServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        try {
            //1、获取前台的参数
            String username = req.getParameter("username");
            String password = req.getParameter("password");

            //2、调用service的check方法得到一个boolean值
            boolean flag= new CheckService().check(username, password);
            // 3.通过rquest对象，获取session对象
            HttpSession session = req.getSession();
            // 4.操作session的API，存储数据
            session.setAttribute("username", username);
            session.setAttribute("password", password);


            //5、创建一个map对象，给map中设置内容
            Map<String,Object> map = new HashMap<String,Object>();
            if (flag){
                map.put("isExist",true);
                map.put("msg","该用户已经存在，请更换");
            }else{
                map.put("isExist",false);
                map.put("msg","该用户可用");

            }
            //5。map转成json 返回给前台
            ObjectMapper om = new ObjectMapper();
            String mapJson = om.writeValueAsString(map);

            resp.getWriter().println(mapJson);


        } catch (SQLException e) {
            e.printStackTrace();
        }



    }
}
